#!/bin/bash

# 部署脚本 - 将应用部署到 /stock/ 路径

echo "开始部署股票量化交易系统..."

# 1. 创建部署目录
echo "创建部署目录..."
sudo mkdir -p /var/www/stock

# 2. 复制文件到部署目录
echo "复制文件到部署目录..."
sudo cp -r ./* /var/www/stock/

# 3. 设置权限
echo "设置文件权限..."
sudo chown -R www-data:www-data /var/www/stock
sudo chmod -R 755 /var/www/stock

# 4. 配置 Nginx (如果使用 Nginx 作为反向代理)
echo "配置 Nginx..."
sudo tee /etc/nginx/sites-available/stock << 'EOF'
server {
    listen 80;
    server_name your-domain.com;  # 请替换为您的域名

    location /stock/ {
        proxy_pass http://localhost:3000/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }
}
EOF

# 启用站点
sudo ln -s /etc/nginx/sites-available/stock /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

# 5. 创建 systemd 服务文件
echo "创建 systemd 服务..."
sudo tee /etc/systemd/system/stock.service << 'EOF'
[Unit]
Description=Stock Trading System
After=network.target

[Service]
Type=exec
WorkingDirectory=/var/www/stock
ExecStart=/usr/bin/node src/server.js
Restart=always
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=stock
Environment=NODE_ENV=production
Environment=BASE_PATH=/stock

[Install]
WantedBy=multi-user.target
EOF

# 6. 启动服务
echo "启动服务..."
sudo systemctl daemon-reload
sudo systemctl enable stock
sudo systemctl start stock

echo "部署完成！应用可通过 http://your-domain.com/stock/ 访问"
echo "请记得将 your-domain.com 替换为您的实际域名"